import { useState, useRef, useCallback, useEffect } from 'react';
import { Play, Pause, ZoomIn, ZoomOut, Scissors, Film, Trash2, Move } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/store';
import { showToast } from '@/store/slices/uiSlice';
import { 
  addVideoClip, 
  splitClip, 
  setZoomLevel, 
  selectClip, 
  removeClip, 
  updateClipPosition, 
  setCurrentTime, 
  togglePlayback 
} from '@/store/slices/timelineSlice';
import { VideoFile } from '@/types/video';
import Button from '@/components/common/Button';
import './timeline-editor.less';

interface TimelineEditorProps {
  className?: string;
}

const TimelineEditor: React.FC<TimelineEditorProps> = ({ className }) => {
  const dispatch = useAppDispatch();
  const { clips, currentTime, zoomLevel, isPlaying, duration, selectedClipId } = useAppSelector(
    state => state.timeline
  );
  const timelineRef = useRef<HTMLDivElement>(null);
  const [draggedClip, setDraggedClip] = useState<{ id: string; startX: number; originalTime: number } | null>(null);

  // 时间格式转换
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 处理剪辑选择
  const handleClipSelect = (clipId: string) => {
    dispatch(selectClip(clipId));
  };

  // 处理剪辑删除
  const handleClipDelete = (clipId: string) => {
    dispatch(removeClip(clipId));
    dispatch(showToast({
      type: 'success',
      title: '删除成功',
      message: '剪辑已从时间线删除'
    }));
  };

  // 处理文件拖放
  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      const file = e.dataTransfer.files[0];
      if (file && file.type.startsWith('video/')) {
        // 创建视频文件对象
        const videoFile: VideoFile = {
          id: Math.random().toString(36).substr(2, 9),
          name: file.name,
          originalName: file.name,
          path: URL.createObjectURL(file),
          size: file.size,
          duration: 0, // 实际应用中需要从文件获取
          format: file.name.split('.').pop() || '',
          codec: 'h264',
          resolution: { width: 1920, height: 1080 },
          bitrate: 0,
          frameRate: 30,
          aspectRatio: '16:9',
          audioTracks: [],
          subtitles: [],
          metadata: { tags: [] },
          createdAt: new Date(),
          updatedAt: new Date(),
        };

        const clip: any = {
          id: `clip-${Date.now()}`,
          trackId: 'track-1',
          sourceFile: videoFile,
          startTime: 0,
          endTime: videoFile.duration,
          trackStartTime: 0,
          duration: videoFile.duration,
          trimStart: 0,
          trimEnd: 0,
          effects: [],
          transitions: [],
          volume: 1,
          muted: false,
        };

        dispatch(addVideoClip(clip));
        dispatch(
          showToast({
            type: 'success',
            title: '添加成功',
            message: `已添加视频片段: ${file.name}`,
          })
        );
      }
    },
    [dispatch]
  );

  // 处理拖放事件
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  // 播放/暂停
  const handlePlayPause = () => {
    dispatch(togglePlayback());
  };

  // 剪辑拖拽开始
  const handleClipDragStart = (clipId: string, e: React.MouseEvent) => {
    e.preventDefault();
    const clip = clips.find(clip => clip.id === clipId);
    if (clip) {
      setDraggedClip({
        id: clipId,
        startX: e.clientX,
        originalTime: clip.trackStartTime
      });
    }
  };

  // 剪辑拖拽
  const handleClipDrag = useCallback((e: MouseEvent) => {
    if (!draggedClip || !timelineRef.current) return;

    const timelineRect = timelineRef.current.getBoundingClientRect();
    const timelineWidth = timelineRect.width;
    const visibleSeconds = 30 / zoomLevel;
    
    const deltaX = e.clientX - draggedClip.startX;
    const deltaTime = (deltaX / timelineWidth) * visibleSeconds;
    
    const newTime = Math.max(0, draggedClip.originalTime + deltaTime);
    
    dispatch(updateClipPosition({ 
      clipId: draggedClip.id, 
      trackStartTime: newTime 
    }));
  }, [draggedClip, zoomLevel, dispatch]);

  // 剪辑拖拽结束
  const handleClipDragEnd = useCallback(() => {
    setDraggedClip(null);
  }, []);

  // 注册拖拽事件
  useEffect(() => {
    if (draggedClip) {
      document.addEventListener('mousemove', handleClipDrag);
      document.addEventListener('mouseup', handleClipDragEnd);
      
      return () => {
        document.removeEventListener('mousemove', handleClipDrag);
        document.removeEventListener('mouseup', handleClipDragEnd);
      };
    }
  }, [draggedClip, handleClipDrag, handleClipDragEnd]);

  // 点击时间线设置播放头位置
  const handleTimelineClick = (e: React.MouseEvent) => {
    if (!timelineRef.current) return;
    
    const timelineRect = timelineRef.current.getBoundingClientRect();
    const clickX = e.clientX - timelineRect.left;
    const timelineWidth = timelineRect.width;
    const visibleSeconds = 30 / zoomLevel;
    
    const newTime = currentTime + ((clickX / timelineWidth) - 0.5) * visibleSeconds;
    dispatch(setCurrentTime(Math.max(0, Math.min(newTime, duration))));
  };

  // 剪辑分割
  const handleSplitClip = () => {
    if (selectedClipId && currentTime) {
      dispatch(
        splitClip({
          clipId: selectedClipId,
          splitTime: currentTime,
        })
      );
    }
  };

  // 缩放控制
  const handleZoomIn = () => {
    dispatch(setZoomLevel(Math.min(zoomLevel * 2, 8)));
  };

  const handleZoomOut = () => {
    dispatch(setZoomLevel(Math.max(zoomLevel / 2, 0.25)));
  };

  // 渲染时间线刻度
  const renderTimelineMarks = () => {
    const marks = [];
    const totalSeconds = duration;
    const visibleSeconds = 30 / zoomLevel; // 可见时间范围

    for (let i = 0; i <= totalSeconds; i += 5) {
      if (i >= currentTime - visibleSeconds / 2 && i <= currentTime + visibleSeconds / 2) {
        marks.push(
          <div
            key={i}
            className='timeline-mark'
            style={{ left: `${((i - currentTime) / visibleSeconds + 0.5) * 100}%` }}
          >
            <div className='timeline-mark-line'></div>
            <span className='timeline-mark-label'>{formatTime(i)}</span>
          </div>
        );
      }
    }
    return marks;
  };

  // 渲染视频剪辑
  const renderVideoClips = () => {
    return clips.map(clip => (
      <div
        key={clip.id}
        className={`timeline-clip ${selectedClipId === clip.id ? 'selected' : ''}`}
        style={{
          left: `${((clip.trackStartTime - currentTime) / (30 / zoomLevel) + 0.5) * 100}%`,
          width: `${(clip.duration / (30 / zoomLevel)) * 100}%`,
        }}
        onClick={() => handleClipSelect(clip.id)}
      >
        <div className='clip-content'>
          <div 
            className='clip-thumbnail'
            onMouseDown={(e) => handleClipDragStart(clip.id, e)}
          >
            <Film className='clip-icon' />
            <div className='clip-overlay'>
              <Move className='drag-handle' size={12} />
            </div>
          </div>
          <div className='clip-info'>
            <span className='clip-name'>{clip.sourceFile.name}</span>
            <span className='clip-duration'>{formatTime(clip.duration)}</span>
          </div>
          {selectedClipId === clip.id && (
            <div className='clip-actions'>
              <button
                className='action-btn delete-btn'
                onClick={(e) => {
                  e.stopPropagation();
                  handleClipDelete(clip.id);
                }}
                title='删除剪辑'
              >
                <Trash2 size={12} />
              </button>
            </div>
          )}
        </div>
      </div>
    ));
  };

  return (
    <div className={`timeline-editor ${className || ''}`}>
      {/* 控制栏 */}
      <div className='timeline-controls'>
        <div className='playback-controls'>
          <Button variant='secondary' size='sm' onClick={handlePlayPause}>
            {isPlaying ? <Pause size={16} /> : <Play size={16} />}
          </Button>
          <Button
            variant='secondary'
            size='sm'
            onClick={handleSplitClip}
            disabled={!selectedClipId}
          >
            <Scissors size={16} />
          </Button>
        </div>

        <div className='zoom-controls'>
          <Button
            variant='secondary'
            size='sm'
            onClick={handleZoomOut}
            disabled={zoomLevel <= 0.25}
          >
            <ZoomOut size={16} />
          </Button>
          <span className='zoom-level'>{zoomLevel}x</span>
          <Button variant='secondary' size='sm' onClick={handleZoomIn} disabled={zoomLevel >= 8}>
            <ZoomIn size={16} />
          </Button>
        </div>

        <div className='time-display'>
          <span>
            {formatTime(currentTime)} / {formatTime(duration)}
          </span>
        </div>
      </div>

      {/* 时间线 */}
      <div
        ref={timelineRef}
        className='timeline-container'
        onDrop={handleDrop}
        onDragOver={handleDragOver}
      >
        {/* 时间刻度 */}
        <div className='timeline-marks'>{renderTimelineMarks()}</div>

        {/* 播放头 */}
        <div className='playhead' style={{ left: '50%' }} />

        {/* 视频轨道 */}
        <div className='video-track'>{renderVideoClips()}</div>

        {/* 音频轨道 */}
        <div className='audio-track'>{/* 音频剪辑渲染 */}</div>
      </div>

      {/* 拖放提示 */}
      {clips.length === 0 && (
        <div className='timeline-drop-zone'>
          <Film className='w-12 h-12 text-gray-400 mb-4' />
          <p className='text-gray-600'>拖放视频文件到此处开始编辑</p>
        </div>
      )}
    </div>
  );
};

export default TimelineEditor;
